package com.qianfeng.openplatform.geteway.fiter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.openplatform.commons.field.RedisKeyPrefix;
import com.qianfeng.openplatform.commons.field.ResponseMessage;
import com.qianfeng.openplatform.commons.field.StaticField;
import com.qianfeng.openplatform.geteway.client.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @author 江江
 * @Date 2020/7/24 14:03
 */
@Component
public class CheckRequiedParamFilter extends ZuulFilter {//过滤
    @Autowired
    private CacheClient cacheClient;

    @Override
    public String filterType() { //指定当前过滤器的类型
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() { //指定过滤器的执行顺序
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 2;
    }

    @Override
    public boolean shouldFilter() {// 开启当前过滤器
        return true;
    }

    @Override // 测试数据http://localhost:9876/openapi?method=servertest01
    public Object run() throws ZuulException {
        //指定过滤器中的具体业务代码
        RequestContext requestContext = RequestContext.getCurrentContext();
        try {
            HttpServletRequest request = requestContext.getRequest();
            Set<Object> keys = cacheClient.sMembers(RedisKeyPrefix.WEB_MASTER_API_MAPPING_PARAMS_KEY);
            if (keys != null) {
                for (Object key : keys) {
                    String value = request.getParameter(key.toString().trim());
          //          System.out.println("CheckRequiedParamFilter---->"+key.toString().trim());
                    if (StringUtils.isEmpty(value)) {
                        throw  new RuntimeException(key.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                requestContext.setSendZuulResponse(false);//拦截响应
                ObjectMapper objectMapper = new ObjectMapper();
                HttpServletResponse response = requestContext.getResponse();
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(objectMapper.writeValueAsString(new ResponseMessage(StaticField.REQEST_NOT_PARAM, "参数错误,没有"+e.getMessage()+"参数....")));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return null;
    }
}













